// pages/passage/passage.js
const QQMapWX = require("../../utils/qqmap-wx.js");
var distance = new QQMapWX({
    key: "DN6BZ-YKMRP-EUHDE-LEBIO-YR736-SRBUI" // 必填
});

const app = getApp();
var getlist = function(that) {
    // var drivers = app.getApi.drivers;
    // var company = wx.getStorageSync("COMPANY");
    var drivers = wx.getStorageSync("DRIVERS");
    wx.showLoading({
        title: "加载中"
    });
    console.log(that.data.url,"---------")
    app.getApi.request(

        "api/DeliveryOrder/List", {
        location: {
          longitude: wx.getStorageSync("longitude"),
          latitude: wx.getStorageSync("latitude"),
          locationAddress: wx.getStorageSync("address")
        },
        DeliveryOrdersStatus: that.data.navIndex,
            drivers: { id: drivers.id, name: drivers.name, tel: drivers.tel },
            ordersSearch: { IsGetGoodsInfo: true },
            pageIndex: that.data.pageIndex,
            pageSize: 10
        },
        "POST",
        res => {
            wx.hideLoading();
            console.log(res)
            if (res.data.responseCode == 1000) {
                //列表数据
                var ordersList = [];
                if (res.data.obj.length > 0) {
                    for (let i = 0; i < res.data.obj.length; i++) {
                        var orderObj = {};

                        if (res.data.obj[i].orders.beginTime) {
                          res.data.obj[i].orders.beginTime = res.data.obj[i].orders.beginTime.substring(5, 10).replace('-', '.')
                        }

                        if (res.data.obj[i].orders.endTime) {
                          res.data.obj[i].orders.endTime = res.data.obj[i].orders.endTime.substring(5, 10).replace('-', '.')
                        }

                        if (res.data.obj[i].orders.beginTimeRang) { //修改取货时间格式
                          console.log(res.data.obj[i].orders.beginTimeRang, )
                          res.data.obj[i].orders.beginTimeRang = res.data.obj[i].orders.beginTimeRang.substring(0, 11)
                        }
                        if (res.data.obj[i].orders.endTimeRang) { //修改送货时间格式

                          res.data.obj[i].orders.endTimeRang = res.data.obj[i].orders.endTimeRang.substring(0, 11)

                        }
                        orderObj.id = res.data.obj[i].orders.id;
                        orderObj.orderNumber = res.data.obj[i].orders.orderNumber;

                        if (res.data.obj[i].orders.consignee) {
                            orderObj.consigneeCity =
                                res.data.obj[i].orders.consignee.consigneeCity;
                        }

                        orderObj.endTime = res.data.obj[i].orders.endTime;
                        ordersList.push(orderObj);
                    }
                    app.getApi.request(
                        "/api/Vehicles/GetDistance", {
                            ordersList: ordersList,
                            location: {
                                longitude: wx.getStorageSync("longitude"),
                                latitude: wx.getStorageSync("latitude"),
                                locationAddress: wx.getStorageSync("address")
                            }
                        },
                        "POST",
                        data => {
                            if (data.data.responseCode == 1000) {
                                //计算距离
                                for (let a in data.data.obj) {
                                    res.data.obj[a].distance = data.data.obj[a].distance.toFixed(
                                        2
                                    );
                                }
                                if (res.data.obj.length > 0) {}
                            } else {}
                            that.setData({
                                items: that.data.items.concat(res.data.obj),
                                onSh: true
                            });
                        },
                        res => {}
                    );
                }

                if (that.data.pageIndex > 1 && res.data.obj.length == 0) {
                    that.setData({
                        isAll: true
                    });
                }
                if (that.data.pageIndex == 1 && res.data.obj.length == 0) {
                    that.setData({
                        noData: true
                    });
                }
            } else {
                wx.showToast({
                    title: '请求失败',
                    icon: 'loading',
                    duration: 2000
                });
            }
            wx.stopPullDownRefresh()
                // if(res.data.)
        },
        res => {}
    );
};

var orderList = function(that) {
    //已完成的订单数据
    // var drivers = app.getApi.drivers;
    var drivers = wx.getStorageSync("DRIVERS");
    // var drivers = app.getApi.drivers;
    wx.showLoading({
        title: "加载中"
    });
    app.getApi.request(
        "/api/Orders/FinishedList", {
            driver: { id: drivers.id, name: drivers.name, tel: drivers.tel },
            location: {
              longitude: wx.getStorageSync("longitude"),
              latitude: wx.getStorageSync("latitude"),
              locationAddress: wx.getStorageSync("address")
            },
            ordersSearch: { IsGetGoodsInfo: true },
            pageIndex: that.data.pageIndex,
            pageSize: 10
        },
        "POST",
        res => {
            wx.hideLoading();
            if (res.data.responseCode == 1000) {
                //列表数据
                that.setData({
                    items: that.data.items.concat(res.data.obj),
                    onSh: true
                });

                if (that.data.pageIndex > 1 && res.data.obj.length == 0) {
                    that.setData({
                        isAll: true
                    });
                }
                if (that.data.pageIndex == 1 && res.data.obj.length == 0) {
                    that.setData({
                        noData: true
                    });
                }
            } else {
                wx.showToast({
                    title: '请求失败',
                    icon: 'loading',
                    duration: 2000
                });
            }
            wx.stopPullDownRefresh()
        },
        res => {}
    );
};

Page({
    /**
     * 页面的初始数据
     */
    data: {
        navIndex: 2,
        pageIndex: 1,
        items: [],
        isAll: false,
        noData: false,
        hidden: false,
        Pullcount: 0,
        url: "api/DeliveryOrder/List",
        onSh: false //首次数据加载是否完成
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function(options) {

      var drivers = wx.getStorageSync("DRIVERS");

        var that = this;
        that.setData({
            items: [],
            isAll: false,
            noData: false,
            hidden: false,
            Pullcount: 0,
            onSh: false,
            pageIndex: 1
        });
        if (that.data.navIndex == 3) {
          getlist(that);
            //orderList(that);
        } else {
            getlist(that);
            console.log(that,"that")
        }

        app.getApi.request(
          "/api/Vehicles/MyVehicles", {
            id: drivers.id,
          },
          "POST",
          res => {
            if (res.data.responseCode == 1000) {
              console.log(res.data, "----------")
              //列表数据
              for (var i = 0; i < res.data.obj.length; i++) {
                if (res.data.obj[i].isVehicleUsing == true) {
                  wx.setNavigationBarTitle({
                    title: "驾驶车辆：" + res.data.obj[i].vehicles.plateNumber
                  })
                }
              }

            } else {
              wx.showToast({
                title: '请求失败',
                icon: 'loading',
                duration: 2000
              });
            }
          },
        );


        app.getApi.request(
          "/api/deliveryorder/Get3StatusList", {
            drivers: { id: drivers.id, name: drivers.name, tel: drivers.tel },
            location: {
              longitude: wx.getStorageSync("longitude"),
              latitude: wx.getStorageSync("latitude"),
              locationAddress: wx.getStorageSync("address")
            },
            pageIndex: that.data.pageIndex,
            pageSize: 10
          },
          "POST",
          res => {
            wx.hideLoading();
            if (res.data.responseCode == 1000) {
              that.setData({
                waitingLoadOrderCount: res.data.obj.waitingLoadOrderCount,
                waitingSendOrderCount: res.data.obj.waitingSendOrderCount,
                finishedOrderCount: res.data.obj.finishedOrderCount                
              })

              //列表数据
            } else {
              wx.showToast({
                title: '请求失败',
                icon: 'loading',
                duration: 2000
              });
            }
          },
        );

    },

    onReachBottom() {
        var that = this;
        if (!that.data.isAll && that.data.Pullcount == 0 && that.data.onSh) {
            that.setData({
                pageIndex: that.data.pageIndex + 1
            });
            that.loadMore = true;
            if (that.data.navIndex == 3) {
                //orderList(that);
                getlist(that);
            } else {
                getlist(that);
            }
        } else {
            that.hidden = true;
        }
    },
    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    nav(e) { //切换tab
        var that = this,
            url = ""; 
        if (e.currentTarget.dataset.index == 2) {
          url = "api/DeliveryOrder/List";
        }
        if (e.currentTarget.dataset.index == 5) {
          url = "api/DeliveryOrder/List";
        }
        console.log(e.currentTarget.dataset.index)
        that.setData({
            navIndex: Number(e.currentTarget.dataset.index),
            items: [],
            url: url,
            isAll: false,
            noData: false,
            hidden: false,
            Pullcount: 0,
            pageIndex: 1
        });
        if (e.currentTarget.dataset.index == 3) {
            //orderList(that);
            getlist(that);
        } else {
            getlist(that);
        }
    },
    order(e) { // 跳转提货
        var item = JSON.stringify(e.currentTarget.dataset.item);
        app.globalData.driversOrders = e.currentTarget.dataset.item;
        wx.navigateTo({
          url: "../pickGood/pickGood?id=" +
                e.currentTarget.dataset.id +
                "&item=" +
                item
        });
    },
    deliveryDetail(e) { //派单详情
        var item = JSON.stringify(e.currentTarget.dataset.item);
        app.globalData.driversOrders = e.currentTarget.dataset.item;
        wx.navigateTo({
          url: "../pickhood/pickhood?id=" +
                e.currentTarget.dataset.id +
                "&item=" +
                item
        });
    },
    // achieveDetails(e) { //完成订单详情
    //     var item = JSON.stringify(e.currentTarget.dataset.item);
    //     app.globalData.driversOrders = e.currentTarget.dataset.item;
    //     wx.navigateTo({
    //       url: "../achieveDetails/achieveDetails?id=" + 
    //             e.currentTarget.dataset.id +
    //             "&item=" +
    //             item
    //     });
    // },
    achieveDetails(e) { //完成订单详情
      var item = JSON.stringify(e.currentTarget.dataset.item);
      app.globalData.driversOrders = e.currentTarget.dataset.item;
      wx.navigateTo({
        url: "../achieve/achieve?id=" +
        e.currentTarget.dataset.id +
        "&item=" +
        item
      });
    },
    /**
     *拨打电话
     */
    makePhoneCall(e) {
        wx.makePhoneCall({
            phoneNumber: e.currentTarget.dataset.number
        });
    },
    toMap: function(e) {
        //进入地图页面

        let address = e.currentTarget.dataset.address;

        distance.geocoder({
            address: address,
            success: function(res) {
                if (res.result) {
                    // that.setData({
                    //     location: res.result
                    // })
                    wx.openLocation({
                        latitude: parseFloat(res.result.location.lat),
                        longitude: parseFloat(res.result.location.lng),
                        scale: 18,
                        address: address
                    });
                } else {
                    that.setData({
                        location: null
                    });
                }
            },
            fail: function(res) {

            },
            complete: function(res) {

            }
        });
    },
    onPullDownRefresh: function() {
        this.onLoad()
    },
    toindex() {
      wx.switchTab({
        url: '../index/index',
      })
    },
    tomy(){
      wx.switchTab({
        url: '../my/my',
      })      
    },
    tocompanyindex(){
      wx.switchTab({
        url: '../company/index/index',
      })   
    },
    topassage() {
      wx.redirectTo({
        url: '../passage/passage',
      })
    }
});